<script setup>
import {CirclePlus, Close, CloseBold, Location, Minus, Setting, UploadFilled} from "@element-plus/icons-vue";
import {ref} from "vue";
import {
  deleteSonChapter, getCourse,
  insertChapter,
  insertSonChapter,
  listCourseChapter,
  listCourseSonChapter, updateChapter, updateSonChapter,
  uploadSonChapterVideo
} from "../../../api/course/course.js";
import router from "../../../router/index.js";
import {ElMessage} from "element-plus";
// 课程对象
const  course=ref({});
// 课程id
const courseId = ref();
// 视频还是章节检测
const isVideoOrTest = ref(0);
courseId.value = localStorage.getItem('courseId')
// 是否增加根级
const isAddRoot = ref(false)
// 是否增加同级
const isAddSon = ref(false)
// 根目录
const rootList = ref([]);
// 子目录
const sonList = ref([])
// 当前选中
const activeIndex = ref('')
// 当前章节
const currentChapter = ref('')

// 文件
const file = ref()

// 鼠标移入事件
const handleMouseOverRoot = () => {
  isAddRoot.value = true;
}
// 鼠标移出事件
const handleMouseLeaveRoot = () => {
  isAddRoot.value = false;
}

// 鼠标移入事件
const handleMouseOverSon = () => {
  isAddSon.value = true;
}

// 鼠标移出事件
const handleMouseLeaveSon = () => {
  isAddSon.value = false;
}

// 增加根目录
const handleAddRoot = () => {
  rootList.value.push({
    name: '新建目录',
    rename: false
  })
  console.log(rootList.value)
}

// 增加子目录
const handleAddSon = () => {
  if (currentChapter.value === '') return;
  if (sonList.value[currentChapter.value] == null) {
    sonList.value[currentChapter.value] = [];
    sonList.value[currentChapter.value].push({
      name: '子目录',
      rename: false
    })
  } else {
    sonList.value[currentChapter.value].push({
      name: '子目录',
      rename: false
    })
  }
  // console.log(sonList.value[currentChapter.value]);
}

// 选中
const handleSelect = (index) => {
  // console.log(index);
  activeIndex.value = index;
  currentChapter.value = index;
}

// 根目录重命名
const handleRootRename = (index) => {
  rootList.value[index].rename = true;
}

// 子目重命名
const handleSonRename = (rootIndex, sonIndex) => {
  event.stopPropagation();
  sonList.value[rootIndex][sonIndex].rename = true;
}


// 根目录重命名完成
const handleFinishRootRename = (index) => {
  rootList.value[index].rename = false;
  // console.log(rootList.value[index].name);
}

// 子目录重命名完成
const handleFinishSonRename = (rootIndex, sonIndex) => {
  sonList.value[rootIndex][sonIndex].rename = false;
  // console.log(sonList.value[activeIndex.value][index].name);
}


// 获取所有章节
// 查看大章节
const handleCourseChapter = async () => {
  await listCourseChapter(courseId.value).then(res => {
    rootList.value = res.data;
    // 增加重命名字段
    rootList.value = rootList.value.map(item => ({
      ...item,
      rename: false
    }))
    // 获取子章节
    for (let i = 0; i < rootList.value.length; i++) {
       handleCourseSonChapter(i, rootList.value[i].id);
    }
    console.log(sonList.value);
  })

}

// 小章节
const handleCourseSonChapter = async (sonIndex, chapterId) => {
  // console.log(chapterId);
  await listCourseSonChapter(chapterId).then(res => {
    sonList.value[sonIndex] = res.data;
    sonList.value.map(item => ({
      ...item,
      rename: false
    }))
    console.log(sonList.value);
  })
}

// 修改当前章节
const handleChangeCurrentChapter = (rootIndex, sonIndex) => {
  activeIndex.value = rootIndex + '-' + sonIndex;
  currentChapter.value = rootIndex;
}

// 处理文件选择事件
const handleFileChange = (files) => {
  file.value = files;
};

// 保存当前章节(查看是否有id)
const handleInsertSonChapter = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      // 解析activeIndex
      let parts = activeIndex.value.split('-');
      const rootIndex = parts[0];
      const sonIndex = parts[1];
      // 说明这是个新的大章节
      console.log(!rootList.value[rootIndex].id);
      if (!rootList.value[rootIndex].id) {
        rootList.value[rootIndex].courseId = courseId.value;
        insertChapter(rootList.value[rootIndex]).then(res => {
          // handleCourseChapter();
        })
      } else if (rootList.value[rootIndex].id) {
        updateChapter(rootList.value[rootIndex]).then(res => {
          // handleCourseChapter();
        })
      }
      // 说明是个新的小章节
      console.log(!sonList.value[rootIndex][sonIndex].id)
      if (!sonList.value[rootIndex][sonIndex].id) {
        sonList.value[rootIndex][sonIndex].chapterId = rootList.value[rootIndex].id;
        insertSonChapter(sonList.value[rootIndex][sonIndex]).then(res => {
            handleUploadVideo(rootIndex, sonIndex);
        })
      } else if (sonList.value[rootIndex][sonIndex].id) {
        updateSonChapter(sonList.value[rootIndex][sonIndex]).then(res => {
            handleUploadVideo(rootIndex, sonIndex);
        })
      }
      console.log(sonList.value[rootIndex][sonIndex].id);
      resolve();
      // 更新视频
    }, 100)
  });
}


// 上传视频
const handleUploadVideo = (rootIndex, sonIndex) => {
  if (file.value) {
    const formData = new FormData();
    formData.append('file', file.value.raw);
    console.log(sonList.value[rootIndex][sonIndex].id);
    uploadSonChapterVideo(sonList.value[rootIndex][sonIndex].id, formData)
  }
}

// 回到章节处
const handleGoCourseChapter = () => {
  router.push("/course/chapter");
}

// 删除子目录
const handleDeleteSonChapter = async (rootIndex, sonIndex) => {
  // 当子目录在数据库存在的时候
  if (sonList.value[rootIndex][sonIndex].id) {
    await deleteSonChapter(sonList.value[rootIndex][sonIndex].id).then(res => {
      ElMessage.success("删除成功");
      handleCourseChapter();
    })
  }
  // 数据库不存在,直接删除即可
  else {
    sonList.value[rootIndex].splice(sonIndex, 1);
  }
}

// 到章节检测生成的页面
const handleGoSonChapterTest = () => {
  isVideoOrTest.value = 2;
  handleInsertSonChapter().then(() => {
    let parts = activeIndex.value.split('-');
    const rootIndex = parts[0];
    const sonIndex = parts[1];
    console.log(sonList.value);
    router.push("/chaptertest/" + sonList.value[rootIndex][sonIndex].id);
  });
}

// 查询课程名称
const handleGetCourse = async () => {
  await getCourse(courseId.value).then(res=>{
    course.value=res.data;
    console.log(res.data);
  })

}
handleGetCourse();
// 查询大章节和小章节
handleCourseChapter();
</script>

<template>
  <div class="common-layout">
    <el-container>
      <el-header style="background: #3a4357;height: 10vh">
        <div style="display: flex; align-items: center; height: 100%;">
          <!--        居中-->
          <span style="color: white;margin-left: 50%">{{course.courseName}}</span>
          <!--        靠右-->
          <el-button type="primary" style="margin-left: auto;margin-right: 10px" @click="handleInsertSonChapter">保存</el-button>
          <!--        靠右-->
          <el-button type="primary" @click="handleGoCourseChapter">完成</el-button>
        </div>
      </el-header>
      <el-container>
        <el-aside width="250px" style="height: 90vh;">
          <div style="display: flex;align-items: center;height: 40px">
            <el-icon
                style="width: 100px"
                @mouseover="handleMouseOverRoot"
                @mouseleave="handleMouseLeaveRoot"
                @click="handleAddRoot"
                :class="{'is-active':isAddRoot}"
            >
              <div style="display: flex;align-items: center;">
                <CirclePlus/>
                <span>根级目录</span>
              </div>
            </el-icon>
            <el-icon
                style="width: 100px"
                @mouseover="handleMouseOverSon"
                @mouseleave="handleMouseLeaveSon"
                @click="handleAddSon"
                :class="{'is-active':isAddSon}"
            >
              <div style="display: flex;align-items: center;">
                <CirclePlus/>
                <span>子目录</span>
              </div>
            </el-icon>
          </div>
          <!--          章节菜单  -->
          <el-menu
              class="el-menu-vertical-demo"
              v-for="(root,rootIndex) in rootList"
              :key="root"
              :default-active="activeIndex"
              :default-openeds="[rootIndex]"
              @open="handleSelect(rootIndex)"
              @close="handleSelect(rootIndex)"
          >
            <!--            根目录-->
            <el-sub-menu
                :index="rootIndex"
                @dblclick="handleRootRename(rootIndex)"
            >
              <template #title>
                <el-icon>
                  <location/>
                </el-icon>
                <span v-if="!root.rename">{{ root.name }}</span>
                <el-input v-model="root.name" v-if="root.rename" @blur="handleFinishRootRename(rootIndex)"></el-input>
              </template>
              <!--              子目录-->
              <el-menu-item :index="rootIndex+'-'+sonIndex" v-for="(son,sonIndex) in sonList[rootIndex]" :key="son"
                            @click="handleChangeCurrentChapter(rootIndex,sonIndex)"
                            @dblclick="handleSonRename(rootIndex,sonIndex)">
                <span v-if="!son.rename">{{ son.name }}</span>
                <el-input v-model="son.name" v-if="son.rename"
                          @blur="handleFinishSonRename(rootIndex,sonIndex)"></el-input>
                <el-icon style="display: flex;margin-left: auto" @click="handleDeleteSonChapter(rootIndex,sonIndex)">
                  <Close/>
                </el-icon>
              </el-menu-item>
            </el-sub-menu>
          </el-menu>
        </el-aside>
        <el-main style="height: 90vh;display:flex;justify-content: center;align-items: center;">
          <el-card style="width: 1100px; height: 80vh">
            <div style="display: flex; align-items: center;justify-content: left;margin-bottom: 10px"
                 v-if="activeIndex!==''">
              <el-button style="border-radius: 14px;" :class="{'video-test': isVideoOrTest===0}"
                         @click="isVideoOrTest=0">1视频
              </el-button>
              <el-button style="border-radius: 14px;" :class="{'video-test': isVideoOrTest===1}"
                         @click="handleGoSonChapterTest">2章节检测
              </el-button>
            </div>
            <div>
              <el-upload
                  ref="uploadRef"
                  class="upload-demo"
                  action="#"
                  :auto-upload="false"
                  drag
                  :on-change="handleFileChange"
                  :file-list="file ? [file] : []"
                  v-if="activeIndex!=='' && isVideoOrTest===0"
                  style="margin-top: 100px"
              >
                <el-icon class="el-icon--upload">
                  <upload-filled/>
                </el-icon>
                <div class="el-upload__text">
                  拖拽视频到此处或者 <em>点击上传</em>
                </div>
                <template #tip>
                  <div class="el-upload__tip">
                    只支持mp4格式
                  </div>
                </template>
              </el-upload>
              <!-- 章节检测表单 -->
            </div>
            <div style="display: flex; justify-content: center; align-items: center;height: 70vh"
                 v-if="activeIndex===''">
              <span>点击章节添加视频和章节检测</span>
            </div>
          </el-card>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<style scoped lang="less">
.is-active {
  color: #00a1d6;
}

.video-test {
  background-color: #409eff;
  color: white
}
</style>